package cn.ug.activity.web.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

public class UploadUtil {
    private static Logger LOG = LoggerFactory.getLogger(UploadUtil.class);

    public static String upload(String accessKey, String secretKey, String bucket, String localFile, String fileName, String fileDomain) {
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(localFile, fileName, upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return fileDomain + putRet.key;
        } catch (QiniuException ex) {
            LOG.error("上传文件出错：" + ex.getMessage());
        }
        return null;
    }
}
